package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.webvo.Catalog2Vo;
import com.atguigu.gulimall.product.vo.webvo.Catalog3Vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.mysql.cj.xdevapi.Collection;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;

/**
 * 使用redisson分布式锁
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    //***********************后台管理实现**************************
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //查询所有分类及子分类，以树形结构组装起来
    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //找到一级分类
        List<CategoryEntity> levelOneMenus = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities)); //设置Children值
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return levelOneMenus;
    }

    //检查菜单是否被引用
    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO       检查当前删除菜单 是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    //查询catelogPath数组以便前端显示
    @Override
    public Long[] findcatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    //联级修改  及修改品牌信息还修改（品牌-菜单分类关联表信息）
    //该操作修改分类菜单名
    @CacheEvict(value ="catelog",allEntries = true)
    @Override
    public void updateCategoryCascade(CategoryEntity category) {
        //更新category表
        baseMapper.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            //品牌-菜单分类关联表信息 操作修改分类菜单名
            QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper();
            wrapper.eq("catelog_id", category.getCatId());
            CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
            entity.setCatelogName(category.getName());
            categoryBrandRelationService.update(entity, wrapper);
        }
    }


    //***********************前端页面实现**************************
    //整合spring-cache完成缓存
    /*
    *  spring-cache的不足
    * 1、读模式：
    * 缓存穿透:查询一个null数据。解决：缓存null数据spring.cache.redis.cache-null-values=true
    * 缓存击穿：大量并发进来同时查询一个正好过期的数据：解决L加锁
    * 缓存雪崩：大量的key同时过期，解决：加随机过期时间
    * 2、写模式：（缓存与数据库一致）
    *  读写加锁
    *  引入canal
    *  直接查数据库
    *原理:
    * CacheManager
    */
    //获取所有一级分类
    //
    @Cacheable(value = {"catelog"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Catagories() {


        List<CategoryEntity> level1 = baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return level1;
    }
  //使用spring-cache
  @Cacheable(value = "catelog",key = "#root.method.name")
  @Override
  public Map<String, List<Catalog2Vo>> getCatalogJson(){
      System.out.println("查了数据库");
      List<CategoryEntity> allLevel = baseMapper.selectList(null);
      List<CategoryEntity> level1 = getLevel1Catagories();
      Map<String, List<Catalog2Vo>> map = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
          List<CategoryEntity> level2 = getLevel(allLevel, v.getCatId());
          List<Catalog2Vo> catalog2Vos = null;
          if (level2 != null) {
              catalog2Vos = level2.stream().map(item2 -> {
                  Catalog2Vo catalog2Vo = new Catalog2Vo(item2.getParentCid().toString(), null, item2.getCatId().toString(), item2.getName());
                  List<CategoryEntity> level3 = getLevel(allLevel, item2.getCatId());
                  if (level3 != null) {
                      List<Catalog3Vo> catalog3Vos = level3.stream().map(item3 -> {
                          Catalog3Vo catalog3Vo = new Catalog3Vo(item3.getParentCid().toString(), item3.getCatId().toString(), item3.getName());
                          return catalog3Vo;
                      }).collect(Collectors.toList());
                      catalog2Vo.setCatalog3List(catalog3Vos);
                  }
                  return catalog2Vo;
              }).collect(Collectors.toList());
          }
          return catalog2Vos;
      }));
      return map;
  }
    //获取一级分类下所有的2、3级分类并加入缓存
    //会出现缓存穿透、缓存雪崩、缓存击穿问题
    //@Override
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        //缓存中存入json字符串,拿出json字符串还有逆转为能用的对象类型
        String catalogjson = redisTemplate.opsForValue().get("catalogjson");
        if (StringUtils.isEmpty(catalogjson)) {
            //缓存中没有 查询数据库
            Map<String, List<Catalog2Vo>> catalogJsonFormDb = getCatalogJsonFormDbRedissonLock();

            return catalogJsonFormDb;
        }
        Map<String, List<Catalog2Vo>> map = JSON.parseObject(catalogjson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return map;
    }

    //从数据库查询 并封装数据
    //1、采用本地锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonFormDb() {
        //解决缓存击穿
        //1、采用本地锁
        synchronized (this) {
            String catalogjson = redisTemplate.opsForValue().get("catalogjson");
            if (!StringUtils.isEmpty(catalogjson)) {
                Map<String, List<Catalog2Vo>> map = JSON.parseObject(catalogjson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
                });
                return map;
            }
            System.out.println("查了数据库");
            List<CategoryEntity> allLevel = baseMapper.selectList(null);
            List<CategoryEntity> level1 = getLevel1Catagories();
            Map<String, List<Catalog2Vo>> map = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                List<CategoryEntity> level2 = getLevel(allLevel, v.getCatId());
                List<Catalog2Vo> catalog2Vos = null;
                if (level2 != null) {
                    catalog2Vos = level2.stream().map(item2 -> {
                        Catalog2Vo catalog2Vo = new Catalog2Vo(item2.getParentCid().toString(), null, item2.getCatId().toString(), item2.getName());
                        List<CategoryEntity> level3 = getLevel(allLevel, item2.getCatId());
                        if (level3 != null) {
                            List<Catalog3Vo> catalog3Vos = level3.stream().map(item3 -> {
                                Catalog3Vo catalog3Vo = new Catalog3Vo(item3.getParentCid().toString(), item3.getCatId().toString(), item3.getName());
                                return catalog3Vo;
                            }).collect(Collectors.toList());
                            catalog2Vo.setCatalog3List(catalog3Vos);
                        }
                        return catalog2Vo;
                    }).collect(Collectors.toList());
                }
                return catalog2Vos;
            }));
            //放入redis中
            String s = JSON.toJSONString(map);
            redisTemplate.opsForValue().set("catalogjson", s, 10, TimeUnit.MINUTES);
            return map;
        }

    }

    //从数据库查询 并封装数据
    //2、采用redisson分布式锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonFormDbRedissonLock() {
        //获取分布式锁
        //锁的名字
        RLock lock = redisson.getLock("catelogjson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dateFromDb;
        try {
            dateFromDb = getDateFromDb();
        } finally {
         lock.unlock();
        }
        return dateFromDb;

    }

    private Map<String, List<Catalog2Vo>> getDateFromDb() {
        //解决缓存击穿
        String catalogjson = redisTemplate.opsForValue().get("catalogjson");
        if (!StringUtils.isEmpty(catalogjson)) {
            Map<String, List<Catalog2Vo>> map = JSON.parseObject(catalogjson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return map;
        }
        System.out.println("查了数据库");
        List<CategoryEntity> allLevel = baseMapper.selectList(null);
        List<CategoryEntity> level1 = getLevel1Catagories();
        Map<String, List<Catalog2Vo>> map = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> level2 = getLevel(allLevel, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (level2 != null) {
                catalog2Vos = level2.stream().map(item2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(item2.getParentCid().toString(), null, item2.getCatId().toString(), item2.getName());
                    List<CategoryEntity> level3 = getLevel(allLevel, item2.getCatId());
                    if (level3 != null) {
                        List<Catalog3Vo> catalog3Vos = level3.stream().map(item3 -> {
                            Catalog3Vo catalog3Vo = new Catalog3Vo(item3.getParentCid().toString(), item3.getCatId().toString(), item3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        //放入redis中
        String s = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catalogjson", s, 10, TimeUnit.MINUTES);
        return map;
    }

    private List<CategoryEntity> getLevel(List<CategoryEntity> allLevel, Long catId) {
        List<CategoryEntity> collect = allLevel.stream().filter(item -> {
            return item.getParentCid().equals(catId);
        }).collect(Collectors.toList());
        return collect;
    }

    public List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = baseMapper.selectById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    //递归查找
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(menu -> {
            menu.setChildren(getChildrens(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {
            //菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }


}